package me.chan.chatting.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import me.chan.chatting.server.factory.LoginServiceFactory;
import me.chan.chatting.server.factory.SessionServiceFactory;
import me.chan.chatting.server.msg.LoginRequestMessage;
import me.chan.chatting.server.msg.LoginResponseMessage;

@ChannelHandler.Sharable
public class LoginInboundHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();

        boolean isLogin = LoginServiceFactory.getInstance()
                .login(username, password);

        SessionServiceFactory.getInstance().bind(ctx.channel(), username);

        LoginResponseMessage message;
        if (isLogin) {
            message = new LoginResponseMessage(true, "登录成功");
        } else {
            message = new LoginResponseMessage(false, "登录失败，请检查用户名或密码");
        }

        ctx.writeAndFlush(message);
    }
}
